<?php

class OrderController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions

			//	'actions'=>array('index','create','update','pay','succ'),

				'actions'=>array('index','create','update','pay','succ','couponview','indexview','payr','alipay'),

				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id)
		));
	}


	public function actionIndexview($id)
	{
		$this->render('Indexview',array(
			'model'=>$this->loadModel($id)
		));
	}


	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
	//   $team=$this->loadModel();
	//	$user=User::model()->findByPk(Yii::app()->user->id);
		$r = $this->loadModel();
		$model=new Order;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Order']))
		{
			$model->attributes=$_POST['Order'];
			$model->team_id=$r['id'];
			$model->city_id=$r['city_id' ];
			$model->user_id=Yii::app()->user->id;

			$model->fare=$r['fare'];
			if($model->fare==0) $model->express='N';

			if($model->quantity>$r['per_number']) { $model->quantity=$r['per_number'];}

			$model->price = $r['team_price'];
			$model->origin = $model->quantity*$model->price+$model->fare;


			if($model->origin<=$r['usermoney'])
			{
				$model->money = 0;
				$model->service='cash';
			}
			else $model->money = $model->origin-$r['usermoney'];

			$randid = rand(1000,9999);
			$times=time();
			$model->pay_id= "go-{$model->team_id}-{$model->quantity}-{$times}-{$randid}";



          	if($model->save())
				$this->redirect(array('view','id'=>$model->id ));
		}

		$this->render('create',array(
			'model'=>$model,
			'result'=>$r
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{	//$r = $this->loadModel($id);
		$model=$this->Model($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Order']))
		{

			$model->attributes=$_POST['Order'];
			$team=Team::model()->findByPk($model->team_id);
			if($model->quantity>$team->per_number)
			{ $model->quantity=$team->per_number;}
			$model->origin = $model->quantity*$model->price+$model->fare;

			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->Model($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}


	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Order');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}


   public function actionSucc($id)
	{
		$this->render('succ',array(
			'model'=>$this->loadModel($id)
		));
	}

	public function createid()
	{
		$id=mt_rand(10000000,99999999);

		return $id;
	}
	public function creatsecret()
	{
		$str = "ABCDEFGHIJKLMNOPQISTUVWXYZ";
		for($j=0;$j<8;$j++)
  		{
    		$secret.= substr($str,rand(0,25),1);
  		}
		return 	$secret;

	}
	public function creatcoupon()
	{
			$model=new Coupon;
			$ordermodel=Order::model()->findByPk((int)$_GET['id']);
			$model->id=$this->createid();
			$model->user_id=$ordermodel->user_id;
			$model->team_id=$ordermodel->team_id;
			$teammodel=Team::model()->findByPk($ordermodel->team_id);
			$model->expire_time=$teammodel->expire_time;
			$model->partner_id=$teammodel->partner_id;
			$model->order_id=$ordermodel->id;
			$model->secret=$this->creatsecret();
			$model->create_time=time();

			try{$model->save();}
			catch (CDbException $e) {$model->id=$this->createid();$model->save();}


	}


		public function actionPay($id)
	{
		$model=$this->loadModel($id);
	 if (isset($_POST['Order'])&&$model['order']->state=='pay')
	{  $this->redirect(array('payr','id'=>$model['order']->id));}

	if(isset($_POST['Order'])&&$model['order']->state=='unpay')
	{
		//	print_r($_POST);

	 		if($_POST['Order']['service']=='alipay')

			{ 	$team_model=Team::model()->findByPk((int)$model['order']->team_id);
				$number=$team_model->now_number+1;
				$return_team=Team::model()->updateByPk((int)$model['order']->team_id, array('now_number'=>$number));
				$team_model=Team::model()->findByPk((int)$model['order']->team_id);
				if($team_model->now_number==$team_model->min_number)
			   {
				 $nowtime=time();
				 $return_team_num=Team::model()->updateByPk((int)$model['order']->team_id, array('reach_time'=>$nowtime));
			    }

			   $return_user = User::model()->updateByPk(Yii::app()->user->id, array('money'=>0));
		//	  $return_order = Order::model()->updateByPk($id, array('state'=>'pay','pay_time'=>time()));

				$this->redirect(array('alipay','id'=>$model['order']->id));
			}

   	}

   if($_POST['Order']['service']=='cash')
		{
				$team_model=Team::model()->findByPk((int)$model['order']->team_id);
				$number=$team_model->now_number+$model['order']->quantity;
				$return_team=Team::model()->updateByPk((int)$model['order']->team_id, array('now_number'=>$number));
				$team_model=Team::model()->findByPk((int)$model['order']->team_id);
			if($team_model->now_number==$team_model->min_number)
			  {	$nowtime=time();
				$return_team_num=Team::model()->updateByPk((int)$model['order']->team_id, array('reach_time'=>$nowtime));
			   }
			    $left = $model['usermoney']-$model['order']->origin;
    		    $return_user = User::model()->updateByPk(Yii::app()->user->id, array('money'=>$left));
			    $return_order = Order::model()->updateByPk($id, array('state'=>'pay','pay_time'=>time()));
			     if($return_user&&$return_order&&$return_team)
			        { if($model['order']->fare==0)
			            {  for($i=0;$i<$model['order']->quantity;$i++ )
			           	   { $this->creatcoupon();}
			            }
			            $this->redirect(array('succ','id'=>$model['order']->id));
		            }
	   }

		$this->render('pay',array(	'model'=>$model ));

   }

    public function actionAlipay($id)
	{
		$this->render('alipay',array(
			'model'=>$this->loadModel($id)
		));
	}



    public function actionPayr($id)
	{
		$this->render('payr',array(
			'model'=>$this->loadModel($id)
		));
	}


	public function actionCouponview($id)
	{
		$orderid='order_id='.$id;
		$dataProvider=new CActiveDataProvider('Coupon',array(
		 'criteria'=>array(
		 'condition'=>$orderid,
		 )));
		$this->render('couponview',array(
			'dataProvider'=>$dataProvider,
		));
	}




	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Order('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Order']))
			$model->attributes=$_GET['Order'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */



	public function loadModel($id=0)
	{
		$res = array();
		if($id==0) {
			if(isset($_GET['id']))
				{$model=Team::model()->findByPk((int)$_GET['id']);
				$res['id']=$model->id;
				$res['fare']=$model->fare;
				$res['team_price']=$model->team_price;
				$res['city_id']=$model->city_id;
				$res['per_number']=$model->per_number;
				$res['title']=$model->title;
				$user=User::model()->findByPk(Yii::app()->user->id);
				$res['usermoney'] = $user->money;
				}

		} else {
			$model=Order::model()->findByPk((int)$id);
			$res['order']=$model;
			$model=Team::model()->findByPk((int)$res['order']->team_id);
			$res['title']=$model->title;
			$res['now_number']=$model->now_number;
			$res['max_number']=$model->max_number;
			$model=User::model()->findByPk(Yii::app()->user->id);
			$res['usermoney']=$model->money;

		}
		if($res===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $res;

	}

	public function Model($id)

	{
		$model=Order::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}




	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='order-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
